package bogus.main;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.swing.ToolTipManager;

import bogus.core.BogusCore;
import bogus.settings.Settings;
import bogus.userInput.Input;
import owg.util.awt.StatefulFrame;

public class BogusMkII
{
    static
    {
	//This shouldn't be a thing
	ToolTipManager.sharedInstance().setDismissDelay(Integer.MAX_VALUE);
    }
    public static void main(String[] args)
    {
	new BogusMkII();
    }

    public static BogusMkII bogus;

    public static StatefulFrame frame;
    public static Panel tlp;

    public static String DIRECTORY;

    public BogusMkII()
    {
	retrieveJarDirectory();
	bogus = this;
	frame = new StatefulFrame("Bogus");
	tlp = new Panel(new BorderLayout());

	frame.add(tlp);

	Settings.settings = Settings.open();
	if(Settings.settings.windowedBounds == null || Settings.settings.windowedBounds.isEmpty())
	{ 
	    frame.pack();
	    frame.setLocationRelativeTo(null);
	}
	else
	{
	    frame.setBounds(Settings.settings.windowedBounds);
	}
	if(Settings.settings.isFullscreen)
	    frame.setExtendedState(Frame.MAXIMIZED_BOTH);

	BogusCore.bogusCore = new BogusCore(tlp, BorderLayout.CENTER);
	Input.registerKeyboard();

	frame.addWindowListener(new WindowAdapter()
	{
	    @Override
	    public void windowClosing(WindowEvent e)
	    {
		//TODO
		Settings.settings.save();
		System.exit(0);
	    }
	});

	frame.setVisible(true);
    }


    public static void retrieveJarDirectory(){
	if (BogusMkII.class.getResource("BogusMkII.class").toString().startsWith("jar") || BogusMkII.class.getResource("BogusMkII.class").toString().startsWith("rsrc")){
	    //Find the directory we're _actually_ running from(double clicky jar on linux yields a nonsense working directory):
	    try{DIRECTORY=URLDecoder.decode(BogusMkII.class.getProtectionDomain().getCodeSource().getLocation().getPath(),"UTF-8");}
	    catch (UnsupportedEncodingException e) {e.printStackTrace();}//That reaaally shouldn't happen. Ever.
	    int fPos  = DIRECTORY.lastIndexOf("/");
	    int bPos  = DIRECTORY.lastIndexOf("\\");
	    DIRECTORY = DIRECTORY.substring(0,Math.max(fPos, bPos)+1);//Ensure we didn't bring the file name with us
	}
	else
	    DIRECTORY = ".";
    }
}
